<template>
  <div class="newVs">
    <div class="mask"></div>
    <div class="new_vs">
      <div class="vs-top">
        <p>{{!$route.query.oid ? '新建资料（厂商订货）':'厂商订货补单'}}</p>
        <i class="el-icon-close" @click="closeNewClerk"></i>
      </div>
      <div class="vs-info">
        <div class="info">
          <p>订货日期</p>
          <el-date-picker v-model="inputDate1" type="date" value-format="yyyy-MM-dd HH:mm:ss" :disabled="supplement"></el-date-picker>
          <p>预交日期</p>
          <el-date-picker v-model="inputDate2" type="date" value-format="yyyy-MM-dd HH:mm:ss" :disabled="supplement"></el-date-picker>
          <p>单号</p>
          <el-input v-model="odd" :disabled="supplement"></el-input>
          <p>配货方式</p>
          <el-select v-model="cooperateWay" :disabled="supplement">
            <el-option v-for="item in cooperateWayList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </div>
        <div class="info">
          <p>厂商编号</p>
          <el-select v-model="manufacturer" :disabled="supplement">
            <el-option v-for="item in manufacturerList" :key="item.value" :label="item.label" :value="item.value">
              <span style="float:left">{{item.value}}</span>
              <span style="float:right">{{item.label}}</span>
            </el-option>
          </el-select>
          <p>厂订序号</p>
          <el-input v-model="inputSequence" disabled></el-input>
          <p>品名</p>
          <el-input v-model="commodityName" disabled></el-input>
          <p>售价</p>
          <el-input v-model="sellingPrice" disabled></el-input>
        </div>
        <div class="info">
          <p>备注</p>
          <el-input style="width:415px" v-model="remark" :disabled="supplement"></el-input>
        </div>

        <el-table id="codeTable" border :data="codeData" class="tb-edit" style="width: 100%;margin-bottom:15px" max-height="148px" @cell-click="cellClick" :header-cell-style="{background:'#f4f4f4',padding:0,height:'40px'}" :cell-style="{padding:0,height:'36px'}">
          <el-table-column :label="header" width="150"></el-table-column>
          <el-table-column prop="colorName" label="颜色" width="100"></el-table-column>
          <template v-for="i in sizeList">
            <el-table-column :prop="i" :label="i" :key="i+Math.random()">
              <template slot-scope="scope">
                <el-input 
                  size="small" 
                  class="innerInp"
                  v-model="scope.row[i]" 
                  @blur="handleInputBlurResult($event,{index:scope.$index,key:i,result:scope.row[i]})" 
                  @keyup.enter.native="inpEnter">
                  </el-input>
                <!-- <span>{{scope.row[i]}}</span> -->
              </template>
            </el-table-column>
          </template>
        </el-table>

        <div class="barcode">
          <p>条码扫描</p>
          <el-switch v-model="isBarcode" active-color="#409EFF" inactive-color="#C0C4CC"></el-switch>
          <p>追加订货</p>
          <el-switch v-model="additional" active-color="#409EFF" inactive-color="#C0C4CC"></el-switch>
        </div>

        <div class="enterBarcode">
          <el-input ref="barcodeInput" v-model="barcode" placeholder="扫描/输入货号或款号，输完按回车" @keyup.enter.native="barcodeEnter($event)"></el-input>
          <span>合计：{{total}}</span>
        </div>

        <el-table height="210px" :data="barcodeData" style="width: 100%" :header-cell-style="{background:'#f4f4f4',padding:0,height:'40px'}" :cell-style="{padding:0,height:'36px'}">
          <el-table-column prop="kindsNumber" label="货号" width="160"></el-table-column>
          <el-table-column prop="colorName" label="颜色" width="100"></el-table-column>
          <el-table-column prop="sizeNo" label="尺码编号" width="100"></el-table-column>
          <el-table-column prop="sum" label="数量" width="100"></el-table-column>
          <el-table-column prop="onePrice" label="单价" ></el-table-column>
          <el-table-column prop="sellingPrice" label="售价"></el-table-column>
          <el-table-column prop="commodityName" label="品名"></el-table-column>
        </el-table>
      </div>

      <div class="vs-btn">
        <el-button @click="closeNewClerk">取消</el-button>
        <el-button @click="saveNew" plain type="primary">保存</el-button>
        <el-button @click="continueInput" type="primary">继续录入</el-button>
      </div>

      <!-- F7弹出框 -->
      <div class="popup" :style="{display:showPopup}">
        <div class="popup_t">
          <p>输入扫描数量</p>
          <i @click="closePopup" class="el-icon-close"></i>
        </div>
        <div class="popup_c">
          <p>请输入扫描数量</p>
          <p>如果不输入则扫描数量为1</p>
          <!-- <el-input v-model="one" style="margin-top:10px" @keyup.enter="()=>{this.showPopup='none'}"></el-input> -->
          <input type="text" class="popup_button" v-model="scanNum" @keyup.enter="()=>{this.showPopup='none'}"></div>
        <div class="popup_b">
          <el-button @click="closePopup">取消</el-button>
          <el-button type="primary" @click="()=>{this.showPopup='none'}">确定</el-button>
        </div>
      </div>
    </div>
  </div>
</template>


<script>

import { orderBuild, orderQuery } from '../../../../network/manufacturerOrder'
import { getKindsNumberList } from '../../../../network/artNo'
import { getBarCode } from '../../../../network/manufacturer'

import today from '../../../../components/mixins/today'

export default {
  mixins: [today],
  created(){
  },
  props: {
    sendData: {
      type: Object,
      default: {}
    },
    manufacturerList: {
      type: Array,
      default: []
    },
    flag: {
      type: Boolean,
      default: false
    }
  },
  data(){
    return {
      // 条码规律详情
      manufacturerBarCode: {},
      // 品牌公司
      brandedCompany: '',
      // 尺码
      knSize: '',
      knSizeList: [],

      showPopup:'none',

      inputDate1: '',
      inputDate2: '',
      odd: '',
      cooperateWay:'配货',
      cooperateWayList:[
        {value:'配货',label:'配货'},
        {value:'订货',label:'订货'},
        {value:'订断',label:'订断'},
        {value:'追断',label:'追断'}
      ],
      manufacturer: '',
      inputSequence: '',
      commodityName: '',
      sellingPrice: '',
      remark: '',
      
      header: '',
      sizeList: [''],
      codeData: [],
      isBarcode: false,
      additional: false,
      barcode: '',

      barcodeData: [],
      tmpBarcodeData: [],

      tmpData: {},
      scanNum: 1,
      beforeScanNum: 1,
      supplement: false,
      total: 0
    }
  },
  watch: {
    sendData(a,b){
      this.inputDate1 = a.inputDate1
      this.inputDate2 = a.inputDate2
      this.manufacturer = a.manufacturer
      this.inputSequence = a.inputSequence
    },
    flag(a,b){
      if (a) {
        if (this.$route.query.oid) {
          this.supplement = true
          this.inputSequence = this.$route.query.oid
          orderQuery(JSON.stringify({
            orderSalesSequence: this.inputSequence,
            totalWay:0})).then(res => {
            if (res.data.code == 200) {
              this.odd = res.data.data[this.inputSequence].receiptsNumber
              this.remark = res.data.data[this.inputSequence].remark
              this.barcodeData = res.data.data[this.inputSequence].manufacturerOrderInfoOneVOList
              this.inputDate1 = this.barcodeData[0].orderTime
              this.inputDate2 = this.barcodeData[0].prepayTime
              this.manufacturer = this.barcodeData[0].manufacturerNo
              this.additional = this.barcodeData[0].isAdd == 1 ? true : false
              this.total = 0
              this.barcodeData.forEach(e => {
                e.sum = e.number
                this.total += Number(e.sum)
              })
            }
          })
        } else {
          this.inputSequence = ''
          this.supplement = false
        }
      }
    },
    barcode(a,b){
      this.barcode = a.toUpperCase().trim()
    }
  },
  methods: {
    closeNewClerk(){
      this.header = ''
      this.odd = ''
      this.cooperateWay ='配货',
      this.inputSequence = ''
      this.commodityName = ''
      this.sellingPrice = ''
      this.remark = ''
      this.isBarcode = false
      this.additional = false
      this.barcode = ''
      this.codeData = []
      this.barcodeData = []
      this.total = 0
      this.$emit('closeNew')
    },
    sibling(e) {
      let s = []
      let pp = e.parentNode.parentNode.children
      for (let j = 0; j < pp.length; j++) {
        let p = pp[j].children
        for(let i = 0, pl = p.length; i < pl; i++) {
          if(p[i] !== e) s.push(p[i])
        }
      }
      return s
    },

    // 保存
    saveNew(){
      if (!this.inputDate1) {
        this.$alert('订货日期不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (!this.inputDate2) {
        this.$alert('预交日期不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (!this.manufacturer) {
        this.$alert('厂商不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      
      // 补单新增的货号放在kindsNumberNumberMap
      // 原有货号不管有没有修改数量，都将原来数据放在kindsNumberMap	

      let kindsNumberNumberMap = {}

      let rfidList = []
      this.barcodeData.forEach(e => {
        kindsNumberNumberMap[e.kindsNumber] = Number(e.sum)
      })

      let d = {
        orderTime: this.inputDate1,
        prepayTime: this.inputDate2,
        orderSalesSequence : this.odd,
        manufacturerNo: this.manufacturer,
        sequence : this.inputSequence,
        remark: this.remark,
        isAppend: this.additional ? 1 : 0,
        cooperateWay: this.cooperateWay,
        kindsNumberMap: kindsNumberNumberMap
      }
      if (this.inputSequence) {
        d.enteringTime = this.searchDateWithHour()
      }

      // console.log(d)
      // return
      orderBuild(JSON.stringify(d)).then(res => {
        if (res.data.code == 200) {
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          let send = {}
          send.inputDate1 = this.inputDate1
          send.inputDate2 = this.inputDate2
          send.manufacturer = this.manufacturer
          send.sequence = res.data.data.sequence
          send.returnVOList = res.data.data.returnVOList
          // 发送到父组件数据
          this.$emit('saveNew', send)

          if (res.data.data.errorDate && res.data.data.errorDate.length) {
            // 导出一个txt文本
            // console.log(String(res.data.data.errorDate))
            this.exportRaw(String(res.data.data.errorDate),'errorDate.txt')
          }
          this.closeNewClerk()
        } else {
          this.$message.error('保存失败')
        }
      })
    },
    // 继续录入
    continueInput(){
      this.commodityName = ''
      this.sellingPrice = ''

      // 之前输入货号录入1条
      if (JSON.stringify(this.tmpData)!='{}') {
        this.barcode = ''
        this.total += Number(this.tmpData.sum)
        if (!this.barcodeData.length) {
          this.barcodeData.push(this.tmpData)
          this.tmpData = {}
        } else {
          for (const i of this.barcodeData) {
            if (i.kindsNumber == this.tmpData.kindsNumber) {
              i.sum = Number(i.sum) + Number(this.tmpData.sum)
              this.tmpData = {}
              return
            }
          }
          this.barcodeData.push(this.tmpData)
          this.tmpData = {}
        }
        return
      }


      // 之前输入款号录入多条
      // console.log(this.codeData)
      let knList = []
      this.codeData.forEach(e => {
        let c = e.colorNo
        this.sizeList.forEach(f => {
          if (this.manufacturerBarCode.styleColorSize) {
            // 型尺色

            if (this.manufacturerBarCode.styleColor) {
              // 款号与尺码之间有 - 

              if (this.manufacturerBarCode.colorSize) {
                // 色号与尺码之间有 - 
                knList.push({
                  kindsNumber:`${this.header}-${f}-${c}`,
                  sum:e[f]
                })
              } else {
                // 色号与尺码之间没有 -  
                knList.push({
                  kindsNumber:`${this.header}-${f}${c}`,
                  sum:e[f]
                })
              }
            } else {
              // 款号与尺码之间没有 - 

              if (this.manufacturerBarCode.colorSize) {
                // 色号与尺码之间有 -  
                knList.push({
                  kindsNumber:`${this.header}${f}-${c}`,
                  sum:e[f]
                }) 
              } else {
                // 色号与尺码之间没有 - 
                knList.push({
                  kindsNumber:`${this.header}${f}${c}`,
                  sum:e[f]
                })
              }
            }
          } else {
            // 型色尺

            if (this.manufacturerBarCode.styleColor) {
              // 款号与颜色之间有 - 

              if (this.manufacturerBarCode.colorSize) {
                // 色号与尺码之间有 -  
                knList.push({
                  kindsNumber:`${this.header}-${c}-${f}`,
                  sum:e[f]
                })
              } else {
                // 色号与尺码之间没有 -  
                knList.push({
                  kindsNumber:`${this.header}-${c}${f}`,
                  sum:e[f]
                })
              }
            } else {
              // 款号与颜色之间没有 - 

              if (this.manufacturerBarCode.colorSize) {
                // 色号与尺码之间有 -  
                knList.push({
                  kindsNumber:`${this.header}${c}-${f}`,
                  sum:e[f]
                })
              } else {
                // 色号与尺码之间没有 - 
                knList.push({
                  kindsNumber:`${this.header}${c}${f}`,
                  sum:e[f]
                }) 
              }
            }
          }
        })
      })
      // console.log(knList)
      if (!knList.length) {
        this.$alert('无数据无法继续录入', '', {
          confirmButtonText: '确定'
        })
        return
      }

      for (const k of knList) {
        for (const l of this.tmpBarcodeData) {
          // console.log(l)
          // console.log(k)
          if (k.kindsNumber == l.kindsNumber) {
            l.sum = k.sum
          }
        }
      }
      // console.log(this.tmpBarcodeData)

      let isExist = 0
      for (const g of this.tmpBarcodeData) {
        if (!Number(g.sum)) continue
        this.total += Number(g.sum)
        if (!this.barcodeData.length) {
          this.barcodeData.push(g)
          continue
        }
        for (const h of this.barcodeData) {
          if (h.kindsNumber == g.kindsNumber) {
            h.sum = Number(h.sum) + Number(g.sum)
            isExist = 0
            break
          }
          isExist = 1
        }
        if (isExist) {
          this.barcodeData.push(g)
        }
      }
      this.$forceUpdate()
      this.barcode = ''
      this.header = ''
      this.codeData = []
    },
    
    // 扫描/输入货号或款号
    barcodeEnter(e){
      if (this.barcode) {
        if (this.isBarcode) {
          // 扫描货号
          getKindsNumberList({kindsNumberStr: this.barcode}).then(res => {
            if (res.data.code == 200) {
              this.commodityName = res.data.data.data[0].commodityName
              this.sellingPrice = res.data.data.data[0].sellingPrice
              this.tmpData = res.data.data.data[0]
              this.tmpData.sum = this.scanNum
              this.tmpData.onePrice = this.tmpData.discount / 10 * this.tmpData.sellingPrice
              this.$refs.barcodeInput.focus()
              this.continueInput()
            }
          })
        } else {
          // 手输型货号
          getKindsNumberList({kindsNumberStr: this.barcode}).then(res => {
            if (res.data.data.data.length) {
              this.$emit('inpNumChange')
              if (res.data.data.data.length) {
                this.commodityName = res.data.data.data[0].commodityName
                this.sellingPrice = res.data.data.data[0].sellingPrice
                this.header = res.data.data.data[0].styleNumber
              }
              // 品牌公司查条码规律详情
              getBarCode({company:res.data.data.data[0].brandedCompany}).then(res => {
                this.manufacturerBarCode = res.data.data[0]
              })
              // console.log(this.manufacturerBarCode)
              // 输入款号显示中间表和尺码信息   ZZZ-AAS
              res.data.data.data.sort((a,b) => {
                return a.relevanceSize.localeCompare(b.relevanceSize)
              })
              let tmp = res.data.data.data
              this.tmpBarcodeData = tmp
              // console.log(tmp)

              // 中间表  尺码表头
              this.sizeList = [tmp[0].size]
              let isExistSize = 0
              for (const i of tmp) {
                for (const j of this.sizeList) {
                  if (j == i.size) {
                    isExistSize = 0
                    break
                  }
                  isExistSize = 1
                }
                if (isExistSize) {
                  this.sizeList.push(i.size)
                }
              }

              // 中间表
              let tmpCodeData = [{colorNo:tmp[0].colorNo,colorName:tmp[0].colorName}]
              let isExistColor = 0
              for (const i of tmp) {
                for (const j of tmpCodeData) {
                  if (j.colorName == i.colorName) {
                    isExistColor = 0
                    break
                  }
                  isExistColor = 1
                }
                if (isExistColor) {
                  tmpCodeData.push({colorNo:i.colorNo,colorName:i.colorName})
                }
              }
              tmpCodeData.forEach(e => {
                this.sizeList.forEach(f => {
                  e[f] = ''
                })
              })
              this.codeData = tmpCodeData
              let codeTable = document.getElementById('codeTable')
              let inputs = codeTable.getElementsByTagName('input')
              // console.log(inputs)
              let int = setInterval(() => {
                clearInterval(int)
                inputs[0].focus()
                inputs[inputs.length - 1].onkeyup = e => {
                  if (window.event.keyCode == 13) {
                    this.continueInput()
                    inputs[inputs.length - 1].onkeyup = () => {}
                  }
                }
              }, 100)
            } else {
              this.$message('此货号/款号无数据')
            }
          })
        }
      }
    },

    closePopup(){
      this.showPopup = 'none'
      this.scanNum = this.beforeScanNum
    },

    //  输入回车/失去焦点统计
    //  index 行索引
    //  result 输入内容
    handleInputBlurResult(e,{index,key,result}) {
      e.target.parentNode.parentNode.parentNode.classList.remove('activeCell')
      let r = /^(0|[1-9][0-9]*|-[1-9][0-9]*)$/
      if (result != 0) {
        result = result.replace(/\b(0+)/gi,"")
      }
      if (!r.test(result) && result) {
        this.$alert('数量请输入整数', '', {
          confirmButtonText: '确定'
        })
        this.codeData[index][key] = 0
        return
      }
      this.codeData[index][key] = result
    },
    cellClick(row, column, cell, event){
      cell.classList.add('activeCell')
      let s = this.sibling(cell)
      // console.log(s)
      s.forEach(e => {
        e.classList.remove('activeCell')
      })
    },
    inpEnter(e){
      e.target.parentNode.parentNode.parentNode.classList.remove('activeCell')
    }
  },
  mounted(){
    let _this = this
    document.onkeydown = function(event){
      let e = event || window.event || arguments.callee.caller.arguments[0]
      if(e && e.keyCode==118){ // 按 F7
        // console.log('an f7')
        if(_this.showPopup == 'none'){
          _this.beforeScanNum = _this.scanNum
          _this.showPopup = 'block'
        }else{
          _this.showPopup = 'none'
        }
      }
    }
  }
}
</script>

<style scoped>
  /* 新建资料 */
  .mask{
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: #000;
    opacity: 0.3;
    z-index: 9;
  }
  .new_vs{
    position: fixed;
    top: 7%;
    left: 50%;
    transform: translateX(-50%);
    width: 1070px;
    max-height: 800px;
    z-index: 99;
    background-color: white;
    overflow: auto;
  }
  .new_vs .vs-top{
    height: 40px;
    background-color: #f8f8f8;
    margin-bottom: 10px;
  }
  .new_vs .vs-top p{
    float: left;
    line-height: 40px;
    padding-left: 20px;
    font-weight: 700;
  }
  .new_vs .vs-top i{
    float: right;
    line-height: 40px;
    padding: 0 16px;
  }

  .new_vs input{
    height: 30px;
    border: solid 1px #DCDFE6;
    border-radius: 5px;
    margin-left: 10px;
  }
  .new_vs input:focus{
    outline: none;
    border: solid 1px #409EFF;
  }

.vs-info {
  padding: 0 20px;
}
.vs-info .info{
  height: 30px;
  margin-bottom: 10px;
}
  .vs-info p{
    display: inline-block;
    width: 80px;
    text-align: right;
    margin-right: 15px;
  }
  .colorBox, .infoBox {
    display: inline;
  }

  .enterBarcode{
    height: 60px;
    background-color: #f2f2f2;
    margin: 15px 0;
  }

  .vs-btn{
    float: right;
    margin: 15px 15px;
  }

  .popup{
    width: 400px;
    height: 200px;
    border: 2px solid #f4f4f4;
    box-shadow: 0 2px 2px 2px #dbdbdb;
    z-index: 999;
    position: absolute;
    left: 50%;
    top: 50%;
    margin:-100px 0 0 -200px;
    background: white;
    display: block;
  }
  .popup_t{
    display: flex;
    justify-content: space-between;
    width: 100%;
    height: 40px;
    background: rgb(244, 244, 244);
    padding: 8px 15px;
  }
  .popup_t p{
    font-weight: 700;
  }
  .popup_c{
    padding: 8px 15px;
  }
  .popup_button{
    margin: 5px 0 0 0;
    width: 94%;
    height: 30px;
    padding:0 10px;
    border: 2px solid #f4f4f4;;
    border-radius: 3px;
  }
  .popup_b{
    margin: 10px 0 0 0;
    padding-left: 230px;
  }
</style>

<style>
  .new_vs .info .el-input , .new_vs .info .el-select{
    width: 160px;
  }
  .new_vs .el-input__inner{
    height: 30px!important;
  }
  .new_vs .el-input__icon{
    line-height: 30px!important;
  }
  .vs-info .barcode .el-switch{
    margin: 0!important;
  }

  .new_vs .enterBarcode .el-input{
    width: 486px;
    margin: 14px 17px;
  }

  .new_vs .colorBox .el-input{
    width: 60px;
    margin-right: 10px;
  }
  .new_vs .colorBox .el-input--suffix{
    width: 90px;
  }

  
</style>
